<?php

namespace app\admin\controller\user;

use app\admin\library\Auth;
use app\common\controller\Backend;
use think\Db;
use think\Request;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{
    protected $relationSearch = true;
    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $k => $v) {
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function index2()
    {
        $admin_id=$this->auth->id;
        $auth=new Auth();
        $gid=$auth->getGroups($admin_id);
        $storearr=db('store')->where('admin_id','=',$admin_id)->column('storeid');
        $storeids=implode(',',$storearr);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if($gid[0]['name']==='店主角色'){
                $total = $this->model
                    ->with('group')
                    ->where($where)
                    ->where('storeid','in',$storeids)
                    ->order($sort, $order)
                    ->count();
                $list = $this->model
                    ->with('group')
                    ->where($where)
                    ->where('storeid','in',$storeids)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }else{
                $total = $this->model
                    ->with('group')
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
                $list = $this->model
                    ->with('group')
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }
            foreach ($list as $k => $v) {
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 会员充值方法
     * @param Request $request
     */
    public function recharge(Request $request)
    {
        $gid=$this->auth->getGroups()[0]['group_id'];
        if ($gid!=8){
            $this->error('只有门店可以给会员充值');
        }
        $uid=$request->param('ids');
        $admin_id=$this->auth->id;
        $storeid=db('store')->where('admin_id','=',$admin_id)->value('storeid');
        $this->assign('uid',$uid);
        $this->assign('storeid',$storeid);
        return $this->view->fetch();
    }

    public function pay(Request $request){
        if($request->isPost()){
            $uid=$request->post('uid');
            $storeid=$request->post('storeid');
            $money=$request->post('money');

            $user=Db::name('user');//用户
            $store=Db::name('store');
            $storemoneylog=Db::name('storemoneylog');//充值流水
            $usermoneylog=Db::name('usermoneylog');
            $usercatcoinlog=Db::name('usercatcoinlog');

            if($money!=999 && $money!=500){
                $this->error('本店只提供999套餐和500套餐');
            }

            Db::startTrans();
            try{
                //1.给用户加余额并且给门店绑定用户为付费用户
                $u=$user->where('id','=',$uid)->find();
                /*if (!empty($u['storeid'])){//会员已经在别的门店
                    if(strpos($u['storeid'],$storeid) !== false){
                        $storeid=$u['storeid'];
                    }else{
                        $storeid=$u['storeid'].','.$storeid;
                    }
                }*/
                $storeuser=db('storeuser');
                //给门店绑定用户
                if(!$storeuser->where(['storeid'=>$storeid,'uid'=>$u['id']])->find()){
                    $storeuser->data(['storeid'=>$storeid,'uid'=>$u['id'],'createtime'=>time()])->insert();
                }
                if($money==999){
                    $newcatcoin=11;
                }else if ($money==500){
                    $newcatcoin=3;
                }
                $isUser=$user->where('id','=',$uid)->update(['money'=>$u['money']+$money,'group_id'=>3,'catcoin'=>$u['catcoin']+$newcatcoin,'totalcatcoin'=>$u['totalcatcoin']+$newcatcoin]);//setField('money',$newmoney);
                //2.给门店加余额;
                $oldstoremoney=$store->where('storeid','=',$storeid)->value('money');
                $isStore=$store->where('storeid','=',$storeid)->update(['money'=>$oldstoremoney+$money]);
                //写日志  1.用户资金日志 2.用户猫币日志 3.门店资金日志
                $logusermoney=$usermoneylog->data(['uid'=>$uid,'storeid'=>$storeid,'money'=>$money,'createtime'=>time(),'remark'=>'充值'])->insert();//用户资金流水
                $logusercatcoin=$usercatcoinlog->data(['uid'=>$uid,'catcoin'=>$newcatcoin,'remark'=>'充值兑换猫币','createtime'=>time(),'storeid'=>$storeid])->insert(); //用户猫币流水
                $storemoney=$storemoneylog->data(['uid'=>$uid,'storeid'=>$storeid,'money'=>$money,'createtime'=>time(),'remark'=>'会员充值'])->insert();//门店资金流水
                if($isUser && $isStore && $logusermoney && $logusercatcoin && $storemoney){
                    Db::commit();
                }
            } catch (\Exception $e) {
                Db::rollback();
                $this->error(__('发生错误操作回滚'));
            }

            $this->success(__('充值成功'));
        }else{
            $this->error('非法请求');
        }
    }

}
